<script
    lang="ts">
/* eslint-disable */
import {getUserPageListApi, saveNewUserApi, deleteUserApi, batchDeleteUserApi} from '@/api/user/user.js'
import {Message} from "element-ui";
import {getAllRoleApi} from '../../../api/role/role.js'
import {getUserRoleByIdApi, updateUserRoleApi} from '../../../api/userRole/userRole.js'

export default {
  data() {
    return {
      userList: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,
      searchCondition: {
        userName: ''
      },
      addDialogFormVisible: false,
      newUser: {
        description: "",
        userCode: "",
        userName: ""
      },
      multipleSelection: [],
      currentStatus: 1,
      //分配
      dispatchRoleDialogVisible: false,
      // 当前登录的用户名
      currentUserName: '',
      currentUserId: 0,
      allRoleList: {},//id:角色名
      role2NameList: {},//角色名:id
      currentUserRoleList: [],//当前的用户所拥有的角色
      newUserRoleList: [],//当前的用户要分配的角色
      roleForm: {
        roleName: ''
      }

    }
  },
  created() {
    this.fetchData(this.currentPage, this.pageSize, this.searchCondition)
  },
  methods: {
    /**
     * 分页条件查询
     * @param currentPage
     * @param pageSize
     */
    fetchData(currentPage, pageSize) {
      getUserPageListApi(currentPage, pageSize, this.searchCondition)
          .then(res => {

            const {records, total, size, current} = res.data

            this.userList = records
            this.total = total
            this.pageSize = size
            this.currentPage = current
          })
          .catch(err => {
            console.log(err)
          })
    },
    /**
     * 分页功能页面大小改变
     * @param pageSize 当前页面的大小
     */
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.fetchData(this.currentPage, this.pageSize, this.searchCondition)
    },
    /**
     * 分页功能当前页改变
     * @param currentPage 当前页
     */
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.fetchData(this.currentPage, this.pageSize, this.searchCondition)

    },
    /**
     * 搜索条件
     */
    search(searchCondition) {
      this.fetchData(this.currentPage, this.pageSize, searchCondition)
    },
    /**
     * 单个元素修改功能
     * @param index
     * @param row
     */
    handleEdit(index, row) {
      console.log(index, row);

    },
    /**
     * 删除当前行元素的功能
     * @param index
     * @param row
     */
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(index, row);
        let res = await deleteUserApi(row.id)
        this.fetchData(this.currentPage, this.pageSize)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })

    },
    /**
     * 添加新用户
     * @param user
     */
    async addNewUser(user) {
      this.addDialogFormVisible = false
      let res = await saveNewUserApi(user)
      this.fetchData(this.currentPage, this.pageSize)
      Message({
        message: res.message,
        type: 'success',
        duration: 5 * 1000
      })
      //todo: 清空form数据不生效
      // this.$refs['addUserForm'].resetFields()
      this.newUser.userName = ''
      this.newUser.userCode = ''
      this.newUser.description = ''
    },
    handleSelectionChange(val) {

      this.multipleSelection = val.map(item => item.id)

    },
    //todo:批量删除功能未完成
    async batchRemove(ids) {
      console.log(ids)
      if (ids.length != 0) {
        let res = await batchDeleteUserApi(ids)
        Message({
          message: res.message,
          type: 'success',
          duration: 5 * 1000
        })
        this.fetchData(this.currentPage, this.pageSize)
      } else {
        Message({
          message: '请选择要删除的数据',
          type: 'warning',
          duration: 5 * 1000
        })
      }
    },
    handleStatusChange(newStatus) {
      console.log(newStatus)

    },
    /**
     * 初始化分配角色对话框
     * @param index
     * @param row
     */
    initDispatchRoleDialog(index, row) {

      this.currentUserName = row.username
      this.currentUserId = row.id
      this.dispatchRoleDialogVisible = true
      //todo:以下方法的执行顺序有Bug
      this.getAllRoleList()
      this.getCurrentUserRoleList()
    },
    async getAllRoleList() {
      let {data} = await getAllRoleApi()
      data.forEach(item => {
        this.allRoleList[item['id']] = item['roleName']
        this.role2NameList[item['roleName']] = item['id']
      })
    },
    //todo:
    async getCurrentUserRoleList() {
      /**
       * 当前的用户所拥有的角色
       */
      let {data} = await getUserRoleByIdApi(this.currentUserId);
      this.currentUserRoleList = data.map(item => {
        return this.allRoleList[item]
      })
    },
    async updateUserRole(currentUserId, newRole) {
      console.log(currentUserId, newRole)
      newRole = newRole.map(roleName => {
        return this.role2NameList[roleName]
      })
      let {res} = await updateUserRoleApi(currentUserId, newRole)

      //关闭对话框
      this.dispatchRoleDialogVisible = false

      console.log(this.currentUserRoleList)

    },
    closeDispatchDialog(){
      this.allRoleList={}
      this.currentUserRoleList=[]
      this.dispatchRoleDialogVisible=false
    }

  }
}
</script>

<template>
  <div>
    <el-form :inline="true"
             :model="searchCondition">
      <el-form-item>
        <el-input v-model="searchCondition.userName"
                  placeholder="请输入查询条件"
                  clearable
                  @clear="fetchData(currentPage,pageSize)"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="search(searchCondition)">查询
        </el-button>
      </el-form-item>
    </el-form>
    <el-button @click="batchRemove(multipleSelection)">批量删除</el-button>

    <el-table
        @selection-change="handleSelectionChange"
        :data="userList"
        style="width: 100%">
      <el-table-column
          type="selection">
      </el-table-column>
      <el-table-column
          prop="username"
          label="用户名">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名">
      </el-table-column>
      <el-table-column
          prop="headUrl"
          label="头像">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间">
      </el-table-column>
      <!--      <el-table-column
                prop="description"
                label="个人描述">
            </el-table-column>-->
      <el-table-column
          prop="status"
          label="状态">
        <template slot-scope="{row}">
          <el-switch
              @change="handleStatusChange"
              v-model="row.status===1"
              active-color="#13ce66"
              inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间">
      </el-table-column>
      <el-table-column
          prop="updateTime"
          label="更新时间">
      </el-table-column>

      <el-table-column
          align="right">
        <template slot="header"
                  slot-scope="scope">
          <el-button
              @click="addDialogFormVisible=true"
              size="mini">
            添加用户
          </el-button>
        </template>
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="success"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="initDispatchRoleDialog(scope.$index,scope.row)">分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 5, 8, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog title="添加新用户"
               :visible.sync="addDialogFormVisible">
      <el-form :model="newUser"
               ref="addUserForm">
        <el-form-item label="用户名">
          <el-input v-model="newUser.userName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户代码">
          <el-input v-model="newUser.userCode"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户描述">
          <el-input v-model="newUser.description"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addNewUser(newUser)">确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色"
               :visible.sync="dispatchRoleDialogVisible">
      currentUserRoleList:{{currentUserRoleList}}
      <br>
      allRoleList:{{allRoleList}}
      <el-form ref="form"
               :model="roleForm"
               label-width="80px">
        <el-form-item label="活动名称">
          <el-input v-model="currentUserName"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="活动性质">
          <el-checkbox-group v-model="currentUserRoleList">
            <el-checkbox v-for="(value,key,index) in allRoleList"
                         :label="value"
                         name="type"
                         :key="key">

            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div slot="footer"
           class="dialog-footer">
        <el-button @click="closeDispatchDialog">取 消</el-button>
        <el-button type="primary"
                   @click="updateUserRole(currentUserId,currentUserRoleList)">确 定
        </el-button>
      </div>
    </el-dialog>


  </div>
</template>

<style scoped>

</style>
